package ch.bfh.mobicomp;

import ch.bfh.mobicomp.ui.in.AlarmActivity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.util.Log;

public class AlarmManager extends BroadcastReceiver {
	public static final String INTENT_ALARM_CANCELLED = "ch.bfh.mobicomp.AlarmManager.ALARM_CANCELLED";
	public static final String INTENT_ALARM_CONFIG_CHANGED = "ch.bfh.mobicomp.AlarmManager.INTENT_ALARM_CONFIG_CHANGED";

	public static final String INTENT_ALARM_ON = "ch.bfh.mobicomp.AlarmManager.INTENT_ALARM_ON";
	public static final String INTENT_ALARM_OFF = "ch.bfh.mobicomp.AlarmManager.INTENT_ALARM_OFF";

	public static final String GLOBAL_ALARM_ON = "ALARM_ON";
	public static final String GLOBAL_ALARM_OFF = "ALARM_OFF";

	@Override
	public void onReceive(Context context, Intent intent) {
		Intent alarmIntent;

		String action = intent.getAction();
		if (action.equals(INTENT_ALARM_CONFIG_CHANGED)) {
			SharedPreferences pref = context.getSharedPreferences(AlarmActivity.SP_NAME,
					Context.MODE_PRIVATE);

			if (pref.getBoolean(AlarmActivity.SP_KEY_SERVICE_STATE, false)) {
				// service on
				alarmIntent = new Intent(SensorService.SERVICE_ON);
				Log.d("ALARM_MANAGER", "Alarm_SERVICE_ON");
			} else {
				// service off
				alarmIntent = new Intent(GLOBAL_ALARM_OFF);
				context.sendBroadcast(alarmIntent);
				Log.d("ALARM_MANAGER", "GLOBAL_ALARM_OFF");
				alarmIntent = new Intent(SensorService.SERVICE_OFF);
				Log.d("ALARM_MANAGER", "Alarm_SERVICE_OFF");
			}
		} else if (action.equals(INTENT_ALARM_CANCELLED)) {
			alarmIntent = new Intent(SensorService.SERVICE_CANCELED);
			Log.d("ALARM_MANAGER", "PutExtra: Alarm_SERVICE_CANCELLED");
		} else if (action.equals(INTENT_ALARM_ON)) {
				alarmIntent = new Intent(GLOBAL_ALARM_ON);
				context.sendBroadcast(alarmIntent);
				Log.d("ALARM_MANAGER", "GLOBAL_ALARM_ON");
			return;
		} else if (action.equals(INTENT_ALARM_OFF)) {
			alarmIntent = new Intent(GLOBAL_ALARM_OFF);
			context.sendBroadcast(alarmIntent);
			Log.d("ALARM_MANAGER", "GLOBAL_ALARM_OFF");
			return;
		} else {
			throw new RuntimeException("Unknown intent");
		}

		context.startService(alarmIntent);
	}
}
